package arithmetic;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

//import javax.xml.bind.DatatypeConverter;

/**
 * @author jiangfeng
 * Created on 2020-04-23
 */
public class TestJDKSerializer {
    public final static String EMPLOYEE_NUM_KEY = "waibaohr:employee:empNum:";
    public static void main(String[] args) throws IOException, ClassNotFoundException {

        // 参考https://blog.csdn.net/lqzkcx3/article/details/79463450
        // https://blog.csdn.net/qq_34446485/article/details/77893765

        byte[] bytes = serialize(EMPLOYEE_NUM_KEY);
        System.out.println(bytes);
        // System.out.println(DatatypeConverter.printHexBinary(bytes));
        // ACED0005740019 77616962616F68723A656D706C6F7965653A656D704E756D3A
        // waibaohr:employee:empNum:

        // source 的编码分析
        // ACED0005740006736F75726365
        //ACED 表示 序列化协议开头
        //0005 序列化格式的版本号
        //74 表示字符串对象TC_STRING
        //0006 类名描述长度:string
        //73 6F 75 72 63 65 表示source的ASCII码
        System.out.println(bytes.length);
        //[B@1218025c
        System.out.println("---");
        for (byte aByte : bytes) {
            // -84-19051160611511111711499101
            System.out.print(aByte);
        }
        System.out.println();
        Object decode = decode(bytes);
        System.out.println(decode);
    }

    public static byte[] serialize(Object object) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream(1024);
        if (!(object instanceof Serializable)) {
        }
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
        objectOutputStream.writeObject(object);
        objectOutputStream.flush();
        return outputStream.toByteArray();
    }

    public static Object decode( byte[] bytes) throws IOException, ClassNotFoundException {
        ObjectInputStream objectInputStream = new ObjectInputStream(new ByteArrayInputStream(bytes));
        try{
            return objectInputStream.readObject();
        }finally{
            objectInputStream.close();
        }
    }
}
